leetcode 53. 最大子数组和 |
您所在的位置:网站首页 › 最大和连续子数组 java › leetcode 53. 最大子数组和 |
题目所属分类
简单的DP 复杂的分治思路 原题链接给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 子数组 是数组中的一个连续部分。 代码案例:输入:nums = [-2,1,-3,4,-1,2,1,-5,4] 输出:6 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。 进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。 题解 简单DP方法O(n)f[i]表示所有以nums[i]结尾的最大值 class Solution { public int maxSubArray(int[] f) { //可以用last表示f[i-1] int ans = f[0] ; int n = f.length ; for(int i = 0,last = 0 ; i public int maxSubArray(int[] nums) { return f(nums,0 , nums.length - 1); } public int f(int[] a,int start,int end){ if(start > end) return Integer.MIN_VALUE; if(start == end ) return a[start]; int mid = (start + end) >> 1 ; int lmax = a[mid] , lsum = 0 , rmax = a[mid] , rsum = 0 ; for(int i = mid ; i >= start ; i -- ){ lsum += a[i]; lmax = Math.max(lmax,lsum); } for(int i = mid ; i |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |